local ROT = require 'lib.rotLua.src.rot'

local TransformGrid = require 'type.transformGrid'

local F = [[
##########
#........#
#.########
#.....####
#.########
#.######.#
##########
]]

local state = ROT.Class:extend()

function state:init(game, play)
    self.game = game
    self.play = play
    self.grid = TransformGrid()
end

function state:update()
    local ox, oy = 7, 3
    local x, y = ox, oy
    for line in F:gmatch('(.-)\n') do
        y = y + 1
        x = ox
        for char in line:gmatch('.') do
            x = x + 1
            self.grid:setCell(x, y, char == '#' and 1 or 0)
        end
    end
    self.game.display:clear()
    self.grid:invoke(function (x, y, val)
        self.game.display:write(val==1 and '#' or '.', x, y)
    end)
end

function state:keypressed(key)
    local game = self.game
    
    if     key==game.keys.move_n then self.grid:rotate(1)  
    elseif key==game.keys.move_w then self.grid:rotate(4)
    elseif key==game.keys.move_e then self.grid:rotate(2)
    elseif key==game.keys.move_s then self.grid:rotate(3)
    elseif key==game.keys.move_ne then self.grid:flip(false, true)
    elseif key==game.keys.move_se then self.grid:flip(true, false)
    elseif key==game.keys.move_nw then self.grid:flip(false, false)
    elseif key==game.keys.scratch then game.state = self.play
    end

end

function state:draw()
    self.game.display:draw()
end


return state
